package net.oschina.aibinxiao.security.base64;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * @Author: AiBinXiao
 * @Description: Base64的三种实现方式
 * @Date: 2017/10/13 10:01
 */

public class MyBase64 {

    private static String src = "imooc security base64";

    public static void main(String[] args) {
        jdkBase64();
        commonsCodecBase64();
        bouncyCastleBase64();
    }

    // 1.使用JDK实现Base64编解码
    public static void jdkBase64(){
        try {
            // 编码
            System.out.println("1.使用JDK实现Base64编解码");
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(src.getBytes());
            System.out.println("encode : " + encode); // encode : aW1vb2Mgc2VjdXJpdHkgYmFzZTY0

            // 解码
            BASE64Decoder decoder = new BASE64Decoder();
            System.out.println(new String(decoder.decodeBuffer(encode))); // imooc security base64
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    // 2.使用Commons Codec实现Base64编解码
    public static void commonsCodecBase64(){
        System.out.println("2.使用Commons Codec实现Base64编解码");
        // 编码
        byte[] encodeBytes = Base64.encodeBase64(src.getBytes());
        System.out.println("encode : " + new String(encodeBytes));

        // 解码
        byte[] decodeBytes = Base64.decodeBase64(encodeBytes);
        System.out.println("decode : " + new String(decodeBytes));
    }

    // 3.使用Bouncy Castle实现Base64编解码
    public static void bouncyCastleBase64(){
        System.out.println("3.使用Bouncy Castle实现Base64编解码");
        // 编码
        byte[] encodeBytes = org.bouncycastle.util.encoders.Base64.encode(src.getBytes());
        System.out.println("encode : " + new String(encodeBytes));
        // 解码
        byte[] decodeBytes = org.bouncycastle.util.encoders.Base64.decode(encodeBytes);
        System.out.println("decode : " + new String(decodeBytes));
    }
}
